<template>
<div class="lists">
  <div v-show="plans.length === 0" class="no">没有计划</div>
    <!-- 今天的计划 -->
    <div class="learn_lists" v-for="item of plans" :key="item.id">
      <div class="learn_list">
        <div class="learn_plan">{{item.plan}}</div>
        <div v-show="!item.begin" class="learn_time">开始时间：{{item.starttime.slice(0,10)}} {{item.starttime.slice(11,19)}}</div>
      </div>
      <div v-show="!item.total" class="learn_choose">
        <span class="learn_str" v-show="(item.show === 1 || item.statue === 2 || item.statue === -1)">{{str}}</span>
        <el-button v-show="!(item.show === 1 || item.statue === 2 || item.statue === -1)" type="success" @click="start(item)">开始</el-button>
        <el-button v-show="(item.show === 1 || item.statue === 2 || item.statue === -1)" type="primary" @click="choose(item)">{{((desc === null) ? '暂停' : desc)}}</el-button>
        <el-button type="info" @click="del(item)">放弃</el-button>
        <el-button v-show="(item.show === 1 || item.statue === 2 || item.statue === -1)" type="danger" @click="end(item)">结束</el-button>
      </div>
      <div v-show="item.total" class="learn_times">共用{{item.times}}分{{item.ss}}秒</div>
    </div>
    <!-- 昨天及以前未完成的计划 -->
    <div>
    <div class="title">昨天及以前的计划</div>
    <div v-show="!(oPlans.length === 0)" class="learn_lists" v-for="item of oPlans" :key="item.id">
    <div class="learn_list">
        <div class="learn_plan">{{item.plan}}</div>
        <div v-show="!item.begin" class="learn_time">开始时间：{{item.starttime.slice(0,10)}} {{item.starttime.slice(11,19)}}</div>
      </div>
      <div v-show="!item.total" class="learn_choose">
        <span class="learn_str" v-show="(item.show === 1 || item.statue === 2 || item.statue === -1)">{{str}}</span>
        <el-button v-show="!(item.show === 1 || item.statue === 2 || item.statue === -1)" type="success" @click="start(item)">开始</el-button>
        <el-button v-show="(item.show === 1 || item.statue === 2 || item.statue === -1)" type="primary" @click="choose(item)">{{((desc === null) ? '暂停' : desc)}}</el-button>
        <el-button type="info" @click="del(item)">放弃</el-button>
        <el-button v-show="(item.show === 1 || item.statue === 2 || item.statue === -1)" type="danger" @click="end(item)">结束</el-button>
      </div>
      <div v-show="item.total" class="learn_times">共用{{item.times}}分{{item.ss}}秒</div>
    </div>
    <div v-show="oPlans.length === 0" class="no">昨日及以前没有未完成的计划</div>
  </div>
<!--折线图：为echarts准备一个具备大小的容器dom-->
  <div id="main" class="ec"></div>
<!-- 今日已完成的任务 -->
  <div class="study_left">
    <h4 class="finish">已完成</h4><hr>
    <div class="f_list f_font" v-show="fplans.length === 0">您今日还没有已完成计划</div>
    <div ref="fList" class="f_list">
      <ul>
        <li class="Learned"  v-for="item of fplans" :key="item.id">
          <div class="finish_plan">{{item.plan}}</div>
          <div class="finish_time">共用{{item.fm}}分{{item.fs}}秒</div>
        </li>
      </ul>
    </div>
    <router-link to="/SelfStudy/finished">
      <div class="more">更多<i class="el-icon-more"></i></div>
    </router-link>
  </div>
</div>
</template>

<script>
// import axios from 'axios'
import echarts from 'echarts'
import axios from 'axios'
import Qs from 'qs'
import BScroll from 'better-scroll'
export default {
  inject: ['reload'],
  props: ['nowDate'],
  computed: {
    time (item) {
      item.h = Math.floor(item.totaltime / 3600)
      item.m = Math.floor(item.totaltime / 60)
      item.s = (item.totaltime % 60)
      return (item.totaltime === 0) ? this.str : (this.toDub(item.h) + ':' + this.toDub(item.m) + ':' + this.toDub(item.s))
    }
  },
  data () {
    return {
      h: 0, // 定义时，分，秒并初始化为0；
      m: 0,
      s: 0,
      times: 0, // 定时器
      str: '00:00:00',
      judge: 0, // 用来判断页面是否开始计时
      desc: '暂停',
      total: false,
      charts: '',
      // opinion: ["1", "3", "3", "4", "5"],
      abscissa: [],
      opinionData: [],
      plans: [],
      fplans: [],
      oPlans: [],
      starttime: 0
    }
  },
  beforeDestroy () { // 销毁定时器
    if (this.timers) {
      clearInterval(this.timers) // 在Vue实例销毁前，清除我们的定时器
    }
  },
  // 调用
  mounted () {
    // 调用折线图
    this.$nextTick(function () {
      this.drawLine('main')
    })
    this.getNowPlans()
    this.getFormerPlans()
    // 得到已完成的任务列表
    axios({
      method: 'post',
      url: '/api/finishPlans'
    }).then(res => {
      console.log(this.fplans.length)
      this.fplans = res.data
      console.log(this.fplans)
      for (var i = 0; i < this.fplans.length; i++) {
        this.fplans[i].fm = Math.floor(this.fplans[i].totaltime / 60)
        this.fplans[i].fs = (this.fplans[i].totaltime % 60)
      }
    })
    this.scroll = new BScroll(this.$refs.fList, {mouseWheel: true})
    this.getLocalStorage()
    if ((this.str !== '00:00:00') && ((this.desc === '暂停') || (this.desc === null))) {
      this.times = setInterval(this.timer, 1000)
      console.log('this.timessssssssss')
    }
  },
  methods: {
    // 获取存储在浏览器中的数据
    getLocalStorage () {
      this.str = window.localStorage.getItem('timed')
      console.log(window.localStorage.getItem('h'), window.localStorage.getItem('h') === 'null')
      // 判断 window.localStorage.getItem('h') 是否为null，为空，则等于0
      this.h = ((window.localStorage.getItem('h') === 'null') ? 0 : parseInt(window.localStorage.getItem('h')))
      this.m = ((window.localStorage.getItem('m') === 'null') ? 0 : parseInt(window.localStorage.getItem('m')))
      this.s = ((window.localStorage.getItem('s') === 'null') ? 0 : parseInt(window.localStorage.getItem('s')))
      this.judge = parseInt(window.localStorage.getItem('judge'))
      this.desc = window.localStorage.getItem('desc')
      console.log(this.str, this.judge, this.desc, 'judgeddd', this.s, typeof (this.h), (this.str !== '00:00:00'), (this.judge === '1'))
    },
    // 获取今日的计划表
    getNowPlans () {
      axios({
        method: 'post',
        url: '/api/newPlans'
      }).then(res => {
        this.plans = res.data
        // 给每一个计划增加一个标签，用来开始和结束按钮
        for (var i = 0; i < this.plans.length; i++) {
          this.plans[i].show = 0
        }
        console.log(this.plans, 'plan')
      })
    },
    // 获取昨日及以前的计划表
    getFormerPlans () {
      axios({
        method: 'post',
        url: '/api/newtimeoutPlans'
      }).then(res => {
        this.oPlans = res.data
        // console.log(this.oPlans, this.oPlans.length, 'oPlan')
      })
    },
    // 计时开始
    start (item) {
      // 开始
      console.log(this.str === 'NaN:NaN:NaN', this.str, this.timed, this.nowDate, 'this.str,timed')
      if ((this.str === '00:00:00') || (this.str === 'NaN:NaN:NaN')) {
        axios({
          method: 'post',
          url: '/api/startPlan',
          data: Qs.stringify({id: item.id})
        }).then(res => {
          console.log(res)
          this.s = 0
          this.h = 0
          this.m = 0
          this.desc = '暂停'
          this.times = setInterval(this.timer, 1000)
          console.log(item.totaltime, 'item.totaltime', item.id)
          this.judge = 1
          item.show = 1
        })
      } else {
        this.$message({
          message: '您已经开启了一个任务，请先完成任务后再开启',
          type: 'warning'
        })
      }
    },
    // 暂停或继续
    choose (item) {
      if (this.desc === '暂停') {
        item.totaltime = this.h * 3600 + this.m * 60 + this.s
        var data = {
          id: item.id,
          totalTime: item.totaltime
        }
        axios({
          method: 'post',
          url: '/api/timeout',
          data: Qs.stringify(data)
        }).then(res => {
          clearInterval(this.times)
          localStorage.desc = this.desc
          this.desc = '继续'
          this.judge = 0
        })
      } else {
        axios({
          method: 'post',
          url: '/api/newPlans'
        }).then(res => {
          console.log('dddd')
          this.times = setInterval(this.timer, 1000)
          localStorage.desc = this.desc
          this.desc = '暂停'
          this.judge = 1
        })
        console.log('choose', this.desc, this.judge)
      }
    },
    // 放弃
    del (item) {
      this.$confirm('确定要放弃该计划吗？')
        .then(_ => {
          this.timer = setTimeout(() => {
            clearInterval(this.times)
            axios({
              method: 'post',
              url: '/api/deletePlan',
              data: Qs.stringify({id: item.id})
            }).then(res => {
              console.log(res)
              this.reload()
              console.log(localStorage.timed, this.str, 'localStorage.timed')
              // 测试时清除因故障而残留的timed
              // localStorage.timed = '00:00:00'
              if (localStorage.timed === this.str) {
                localStorage.timed = '00:00:00'
                localStorage.h = 0
                localStorage.m = 0
                localStorage.s = 0
                localStorage.judge = 0
              }
            })
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false
            }, 400)
          }, 500)
        })
        .catch(_ => {})
    },
    end (item) {
      var data = {
        id: item.id,
        totalTime: item.totaltime
      }
      axios({
        method: 'post',
        url: '/api/finish',
        data: Qs.stringify(data)
      }).then(res => {
        console.log(res)
        clearInterval(this.times)
        // 统计共看了多少分钟多少秒
        // console.log(this.h, this.m, this.s, this.time, 'this.time', item, item.times)
        item.ss = this.s
        item.totaltime = this.h * 3600 + this.m * 60 + this.s
        item.total = true
        console.log(this.str, this.times, 'this.times', item.ss, item.totaltime)
        var localStorage = window.localStorage
        localStorage.timed = '00:00:00'
        localStorage.h = 0
        localStorage.m = 0
        localStorage.s = 0
        localStorage.judge = 0
        this.reload()
      })
    },
    // 计时器
    timer () {
      // 定义计时函数
      this.s = this.s + 1 // 秒
      if (this.s >= 60) {
        this.s = 0
        this.m = this.m + 1 // 分钟
      }
      if (this.m >= 60) {
        this.m = 0
        this.h = this.h + 1 // 小时
      }
      this.str =
        this.toDub(this.h) + ':' + this.toDub(this.m) + ':' + this.toDub(this.s)
    },
    // 给不到10的数字加上0
    toDub (n) {
      // 补0操作
      if (n < 10) {
        return '0' + n
      } else {
        return '' + n
      }
    },
    // 折线图
    drawLine (id) {
      // 获取过去七天完成任务数量
      axios({
        method: 'post',
        url: '/api/countChart'
      }).then(res => {
        // console.log(res.data)
        for (var key in res.data) {
          this.abscissa.push(key)
          this.opinionData.push((res.data[key]))
        }
        // 基于准备好的dom，初始化echarts实例
        this.charts = echarts.init(document.getElementById(id))
        // 使用刚指定的配置项和数据显示图表。
        this.charts.setOption({
          // 提示框组件
          tooltip: {
            trigger: 'axis'
          },
          legend: { // 说明文字的设置
            data: ['近七日情况']
          },
          // 直角坐标系底板
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          // 直角坐标系 X 轴
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.abscissa,
            name: '日期',
            nameTextStyle: {
              fontWeight: 300,
              fontSize: 10
            }
          },
          // 直角坐标系 Y 轴
          yAxis: {
            type: 'value',
            name: '完成任务个数',
            min: 0,
            max: 20,
            nameTextStyle: {
              fontWeight: 300,
              fontSize: 10
            }
          },
          // 当天完成任务的情况
          series: [{
            name: '完成任务个数',
            type: 'line',
            stack: '总量',
            data: this.opinionData,
            itemStyle: {
              color: 'skyblue'
            }
          }]
        })
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.lists
  background-color white
  padding-top .5rem
  padding-bottom 3rem
  .no
    font-size 2rem
    text-align center
    line-height 18rem
    padding-right 5rem
  .title
    width 96%
    margin 2rem auto
    padding-left 1rem
    background-color rgba(0 0 0 0.1)
  .learn_lists
    width 90%
    margin 2rem auto
    position relative
    .learn_list
      padding 1rem
      box-shadow 0 0 0.266667rem rgba(131, 171, 175, 0.5)
      border-radius 0.3rem
      .learn_time
        height 1rem
        line-height 1rem
      .learn_plan
        height 3rem
        line-height 2rem
        font-size 1.2rem
    .learn_choose
      position absolute
      right 1rem
      top 1.5rem
      .learn_str
        margin 0 10rem
        font-size 2rem
        line-height 3rem
    .learn_times
      position absolute
      right 1rem
      bottom 1rem
      font-size 1rem
      color #909399
  .ec
    position fixed!important
    right 5%
    top 10%
    background-color white
    width 21%
    height 40%
  .study_left
    position fixed
    right 5%
    top 52%
    width 21%
    height 46%
    .finish
      height 1.2rem
      line-height 1.2rem
      padding .5rem .5rem
      font-size 1rem
      z-index 9
      background-color white
    .f_list
      height 17.4rem
      overflow hidden
      background-color white
      padding-top .5rem
      .Learned
        width 80%
        margin .5rem auto
        padding 1.2rem 1rem
        box-shadow: 0 0 0.266667rem rgba(131,171,175,.5);
        border-radius .5rem
        .finish_plan
          font-size 1rem
        .finish_time
          float right
          color #909399
    .f_font
      font-size 1.5rem
      text-align center
      line-height 17.4rem
    .more
      position absolute
      right 3%
      top 2%
      color #909399
</style>
